package org.dreamwork.jasmine2.misc;

import org.dreamwork.misc.Captcha;
import org.dreamwork.misc.CaptchaType;
import org.dreamwork.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: seth.yang
 * Date: 13-12-6
 * Time: 下午2:44
 */
@WebServlet (urlPatterns = "/captcha")
public class CaptchaServlet extends HttpServlet {
    @Override
    protected void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "No-cache");
        response.setDateHeader("Expires", 0) ;
        response.setContentType("image/jpg") ;

        Captcha captcha = new Captcha ();

        String s_width = request.getParameter ("width"),
               s_height = request.getParameter ("height"),
               s_type = request.getParameter ("type"),
               s_length = request.getParameter ("length"),
               s_lines = request.getParameter ("line"),
               s_scale = request.getParameter ("scale"),
               s_rotate = request.getParameter ("rotate");
        if (!StringUtil.isEmpty (s_width)) {
            captcha.setWidth (Integer.parseInt (s_width));
        }
        if (!StringUtil.isEmpty (s_height)) {
            captcha.setHeight (Integer.parseInt (s_height));
        }
        if (!StringUtil.isEmpty (s_length)) {
            captcha.setLength (Integer.parseInt (s_length));
        }
        if (!StringUtil.isEmpty (s_type)) {
            captcha.setType (CaptchaType.parse (s_type));
        }
        if (!StringUtil.isEmpty (s_lines)) {
            captcha.setRandomLines (Boolean.valueOf (s_lines));
        }
        if (!StringUtil.isEmpty (s_scale)) {
            captcha.setScaleChars (Boolean.valueOf (s_scale));
        }
        if (!StringUtil.isEmpty (s_rotate)) {
            captcha.setRotateChars (Boolean.valueOf (s_rotate));
        }

        HttpSession session = request.getSession ();
        captcha.generateContent ();
        CaptchaManager.save (captcha, session);
        captcha.writeImage (response.getOutputStream ());
    }
}